home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / mailbox.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  74.1 KB  |  2,126 lines

  1. #! /usr/bin/python2.6
  2.  
  3. """Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
  4.  
  5. # Notes for authors of new mailbox subclasses:
  6. #
  7. # Remember to fsync() changes to disk before closing a modified file
  8. # or returning from a flush() method.  See functions _sync_flush() and
  9. # _sync_close().
  10.  
  11. import sys
  12. import os
  13. import time
  14. import calendar
  15. import socket
  16. import errno
  17. import copy
  18. import email
  19. import email.message
  20. import email.generator
  21. import StringIO
  22. try:
  23.     if sys.platform == 'os2emx':
  24.         # OS/2 EMX fcntl() not adequate
  25.         raise ImportError
  26.     import fcntl
  27. except ImportError:
  28.     fcntl = None
  29.  
  30. import warnings
  31. with warnings.catch_warnings():
  32.     if sys.py3kwarning:
  33.         warnings.filterwarnings("ignore", ".*rfc822 has been removed",
  34.                                 DeprecationWarning)
  35.     import rfc822
  36.  
  37. __all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
  38.             'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
  39.             'BabylMessage', 'MMDFMessage', 'UnixMailbox',
  40.             'PortableUnixMailbox', 'MmdfMailbox', 'MHMailbox', 'BabylMailbox' ]
  41.  
  42. class Mailbox:
  43.     """A group of messages in a particular place."""
  44.  
  45.     def __init__(self, path, factory=None, create=True):
  46.         """Initialize a Mailbox instance."""
  47.         self._path = os.path.abspath(os.path.expanduser(path))
  48.         self._factory = factory
  49.  
  50.     def add(self, message):
  51.         """Add message and return assigned key."""
  52.         raise NotImplementedError('Method must be implemented by subclass')
  53.  
  54.     def remove(self, key):
  55.         """Remove the keyed message; raise KeyError if it doesn't exist."""
  56.         raise NotImplementedError('Method must be implemented by subclass')
  57.  
  58.     def __delitem__(self, key):
  59.         self.remove(key)
  60.  
  61.     def discard(self, key):
  62.         """If the keyed message exists, remove it."""
  63.         try:
  64.             self.remove(key)
  65.         except KeyError:
  66.             pass
  67.  
  68.     def __setitem__(self, key, message):
  69.         """Replace the keyed message; raise KeyError if it doesn't exist."""
  70.         raise NotImplementedError('Method must be implemented by subclass')
  71.  
  72.     def get(self, key, default=None):
  73.         """Return the keyed message, or default if it doesn't exist."""
  74.         try:
  75.             return self.__getitem__(key)
  76.         except KeyError:
  77.             return default
  78.  
  79.     def __getitem__(self, key):
  80.         """Return the keyed message; raise KeyError if it doesn't exist."""
  81.         if not self._factory:
  82.             return self.get_message(key)
  83.         else:
  84.             return self._factory(self.get_file(key))
  85.  
  86.     def get_message(self, key):
  87.         """Return a Message representation or raise a KeyError."""
  88.         raise NotImplementedError('Method must be implemented by subclass')
  89.  
  90.     def get_string(self, key):
  91.         """Return a string representation or raise a KeyError."""
  92.         raise NotImplementedError('Method must be implemented by subclass')
  93.  
  94.     def get_file(self, key):
  95.         """Return a file-like representation or raise a KeyError."""
  96.         raise NotImplementedError('Method must be implemented by subclass')
  97.  
  98.     def iterkeys(self):
  99.         """Return an iterator over keys."""
  100.         raise NotImplementedError('Method must be implemented by subclass')
  101.  
  102.     def keys(self):
  103.         """Return a list of keys."""
  104.         return list(self.iterkeys())
  105.  
  106.     def itervalues(self):
  107.         """Return an iterator over all messages."""
  108.         for key in self.iterkeys():
  109.             try:
  110.                 value = self[key]
  111.             except KeyError:
  112.                 continue
  113.             yield value
  114.  
  115.     def __iter__(self):
  116.         return self.itervalues()
  117.  
  118.     def values(self):
  119.         """Return a list of messages. Memory intensive."""
  120.         return list(self.itervalues())
  121.  
  122.     def iteritems(self):
  123.         """Return an iterator over (key, message) tuples."""
  124.         for key in self.iterkeys():
  125.             try:
  126.                 value = self[key]
  127.             except KeyError:
  128.                 continue
  129.             yield (key, value)
  130.  
  131.     def items(self):
  132.         """Return a list of (key, message) tuples. Memory intensive."""
  133.         return list(self.iteritems())
  134.  
  135.     def has_key(self, key):
  136.         """Return True if the keyed message exists, False otherwise."""
  137.         raise NotImplementedError('Method must be implemented by subclass')
  138.  
  139.     def __contains__(self, key):
  140.         return self.has_key(key)
  141.  
  142.     def __len__(self):
  143.         """Return a count of messages in the mailbox."""
  144.         raise NotImplementedError('Method must be implemented by subclass')
  145.  
  146.     def clear(self):
  147.         """Delete all messages."""
  148.         for key in self.iterkeys():
  149.             self.discard(key)
  150.  
  151.     def pop(self, key, default=None):
  152.         """Delete the keyed message and return it, or default."""
  153.         try:
  154.             result = self[key]
  155.         except KeyError:
  156.             return default
  157.         self.discard(key)
  158.         return result
  159.  
  160.     def popitem(self):
  161.         """Delete an arbitrary (key, message) pair and return it."""
  162.         for key in self.iterkeys():
  163.             return (key, self.pop(key))     # This is only run once.
  164.         else:
  165.             raise KeyError('No messages in mailbox')
  166.  
  167.     def update(self, arg=None):
  168.         """Change the messages that correspond to certain keys."""
  169.         if hasattr(arg, 'iteritems'):
  170.             source = arg.iteritems()
  171.         elif hasattr(arg, 'items'):
  172.             source = arg.items()
  173.         else:
  174.             source = arg
  175.         bad_key = False
  176.         for key, message in source:
  177.             try:
  178.                 self[key] = message
  179.             except KeyError:
  180.                 bad_key = True
  181.         if bad_key:
  182.             raise KeyError('No message with key(s)')
  183.  
  184.     def flush(self):
  185.         """Write any pending changes to the disk."""
  186.         raise NotImplementedError('Method must be implemented by subclass')
  187.  
  188.     def lock(self):
  189.         """Lock the mailbox."""
  190.         raise NotImplementedError('Method must be implemented by subclass')
  191.  
  192.     def unlock(self):
  193.         """Unlock the mailbox if it is locked."""
  194.         raise NotImplementedError('Method must be implemented by subclass')
  195.  
  196.     def close(self):
  197.         """Flush and close the mailbox."""
  198.         raise NotImplementedError('Method must be implemented by subclass')
  199.  
  200.     def _dump_message(self, message, target, mangle_from_=False):
  201.         # Most files are opened in binary mode to allow predictable seeking.
  202.         # To get native line endings on disk, the user-friendly \n line endings
  203.         # used in strings and by email.Message are translated here.
  204.         """Dump message contents to target file."""
  205.         if isinstance(message, email.message.Message):
  206.             buffer = StringIO.StringIO()
  207.             gen = email.generator.Generator(buffer, mangle_from_, 0)
  208.             gen.flatten(message)
  209.             buffer.seek(0)
  210.             target.write(buffer.read().replace('\n', os.linesep))
  211.         elif isinstance(message, str):
  212.             if mangle_from_:
  213.                 message = message.replace('\nFrom ', '\n>From ')
  214.             message = message.replace('\n', os.linesep)
  215.             target.write(message)
  216.         elif hasattr(message, 'read'):
  217.             while True:
  218.                 line = message.readline()
  219.                 if line == '':
  220.                     break
  221.                 if mangle_from_ and line.startswith('From '):
  222.                     line = '>From ' + line[5:]
  223.                 line = line.replace('\n', os.linesep)
  224.                 target.write(line)
  225.         else:
  226.             raise TypeError('Invalid message type: %s' % type(message))
  227.  
  228.  
  229. class Maildir(Mailbox):
  230.     """A qmail-style Maildir mailbox."""
  231.  
  232.     colon = ':'
  233.  
  234.     def __init__(self, dirname, factory=rfc822.Message, create=True):
  235.         """Initialize a Maildir instance."""
  236.         Mailbox.__init__(self, dirname, factory, create)
  237.         if not os.path.exists(self._path):
  238.             if create:
  239.                 os.mkdir(self._path, 0700)
  240.                 os.mkdir(os.path.join(self._path, 'tmp'), 0700)
  241.                 os.mkdir(os.path.join(self._path, 'new'), 0700)
  242.                 os.mkdir(os.path.join(self._path, 'cur'), 0700)
  243.             else:
  244.                 raise NoSuchMailboxError(self._path)
  245.         self._toc = {}
  246.  
  247.     def add(self, message):
  248.         """Add message and return assigned key."""
  249.         tmp_file = self._create_tmp()
  250.         try:
  251.             self._dump_message(message, tmp_file)
  252.         finally:
  253.             _sync_close(tmp_file)
  254.         if isinstance(message, MaildirMessage):
  255.             subdir = message.get_subdir()
  256.             suffix = self.colon + message.get_info()
  257.             if suffix == self.colon:
  258.                 suffix = ''
  259.         else:
  260.             subdir = 'new'
  261.             suffix = ''
  262.         uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
  263.         dest = os.path.join(self._path, subdir, uniq + suffix)
  264.         try:
  265.             if hasattr(os, 'link'):
  266.                 os.link(tmp_file.name, dest)
  267.                 os.remove(tmp_file.name)
  268.             else:
  269.                 os.rename(tmp_file.name, dest)
  270.         except OSError, e:
  271.             os.remove(tmp_file.name)
  272.             if e.errno == errno.EEXIST:
  273.                 raise ExternalClashError('Name clash with existing message: %s'
  274.                                          % dest)
  275.             else:
  276.                 raise
  277.         if isinstance(message, MaildirMessage):
  278.             os.utime(dest, (os.path.getatime(dest), message.get_date()))
  279.         return uniq
  280.  
  281.     def remove(self, key):
  282.         """Remove the keyed message; raise KeyError if it doesn't exist."""
  283.         os.remove(os.path.join(self._path, self._lookup(key)))
  284.  
  285.     def discard(self, key):
  286.         """If the keyed message exists, remove it."""
  287.         # This overrides an inapplicable implementation in the superclass.
  288.         try:
  289.             self.remove(key)
  290.         except KeyError:
  291.             pass
  292.         except OSError, e:
  293.             if e.errno != errno.ENOENT:
  294.                 raise
  295.  
  296.     def __setitem__(self, key, message):
  297.         """Replace the keyed message; raise KeyError if it doesn't exist."""
  298.         old_subpath = self._lookup(key)
  299.         temp_key = self.add(message)
  300.         temp_subpath = self._lookup(temp_key)
  301.         if isinstance(message, MaildirMessage):
  302.             # temp's subdir and suffix were specified by message.
  303.             dominant_subpath = temp_subpath
  304.         else:
  305.             # temp's subdir and suffix were defaults from add().
  306.             dominant_subpath = old_subpath
  307.         subdir = os.path.dirname(dominant_subpath)
  308.         if self.colon in dominant_subpath:
  309.             suffix = self.colon + dominant_subpath.split(self.colon)[-1]
  310.         else:
  311.             suffix = ''
  312.         self.discard(key)
  313.         new_path = os.path.join(self._path, subdir, key + suffix)
  314.         os.rename(os.path.join(self._path, temp_subpath), new_path)
  315.         if isinstance(message, MaildirMessage):
  316.             os.utime(new_path, (os.path.getatime(new_path),
  317.                                 message.get_date()))
  318.  
  319.     def get_message(self, key):
  320.         """Return a Message representation or raise a KeyError."""
  321.         subpath = self._lookup(key)
  322.         f = open(os.path.join(self._path, subpath), 'r')
  323.         try:
  324.             if self._factory:
  325.                 msg = self._factory(f)
  326.             else:
  327.                 msg = MaildirMessage(f)
  328.         finally:
  329.             f.close()
  330.         subdir, name = os.path.split(subpath)
  331.         msg.set_subdir(subdir)
  332.         if self.colon in name:
  333.             msg.set_info(name.split(self.colon)[-1])
  334.         msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
  335.         return msg
  336.  
  337.     def get_string(self, key):
  338.         """Return a string representation or raise a KeyError."""
  339.         f = open(os.path.join(self._path, self._lookup(key)), 'r')
  340.         try:
  341.             return f.read()
  342.         finally:
  343.             f.close()
  344.  
  345.     def get_file(self, key):
  346.         """Return a file-like representation or raise a KeyError."""
  347.         f = open(os.path.join(self._path, self._lookup(key)), 'rb')
  348.         return _ProxyFile(f)
  349.  
  350.     def iterkeys(self):
  351.         """Return an iterator over keys."""
  352.         self._refresh()
  353.         for key in self._toc:
  354.             try:
  355.                 self._lookup(key)
  356.             except KeyError:
  357.                 continue
  358.             yield key
  359.  
  360.     def has_key(self, key):
  361.         """Return True if the keyed message exists, False otherwise."""
  362.         self._refresh()
  363.         return key in self._toc
  364.  
  365.     def __len__(self):
  366.         """Return a count of messages in the mailbox."""
  367.         self._refresh()
  368.         return len(self._toc)
  369.  
  370.     def flush(self):
  371.         """Write any pending changes to disk."""
  372.         return  # Maildir changes are always written immediately.
  373.  
  374.     def lock(self):
  375.         """Lock the mailbox."""
  376.         return
  377.  
  378.     def unlock(self):
  379.         """Unlock the mailbox if it is locked."""
  380.         return
  381.  
  382.     def close(self):
  383.         """Flush and close the mailbox."""
  384.         return
  385.  
  386.     def list_folders(self):
  387.         """Return a list of folder names."""
  388.         result = []
  389.         for entry in os.listdir(self._path):
  390.             if len(entry) > 1 and entry[0] == '.' and \
  391.                os.path.isdir(os.path.join(self._path, entry)):
  392.                 result.append(entry[1:])
  393.         return result
  394.  
  395.     def get_folder(self, folder):
  396.         """Return a Maildir instance for the named folder."""
  397.         return Maildir(os.path.join(self._path, '.' + folder),
  398.                        factory=self._factory,
  399.                        create=False)
  400.  
  401.     def add_folder(self, folder):
  402.         """Create a folder and return a Maildir instance representing it."""
  403.         path = os.path.join(self._path, '.' + folder)
  404.         result = Maildir(path, factory=self._factory)
  405.         maildirfolder_path = os.path.join(path, 'maildirfolder')
  406.         if not os.path.exists(maildirfolder_path):
  407.             os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
  408.                 0666))
  409.         return result
  410.  
  411.     def remove_folder(self, folder):
  412.         """Delete the named folder, which must be empty."""
  413.         path = os.path.join(self._path, '.' + folder)
  414.         for entry in os.listdir(os.path.join(path, 'new')) + \
  415.                      os.listdir(os.path.join(path, 'cur')):
  416.             if len(entry) < 1 or entry[0] != '.':
  417.                 raise NotEmptyError('Folder contains message(s): %s' % folder)
  418.         for entry in os.listdir(path):
  419.             if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
  420.                os.path.isdir(os.path.join(path, entry)):
  421.                 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
  422.                                     (folder, entry))
  423.         for root, dirs, files in os.walk(path, topdown=False):
  424.             for entry in files:
  425.                 os.remove(os.path.join(root, entry))
  426.             for entry in dirs:
  427.                 os.rmdir(os.path.join(root, entry))
  428.         os.rmdir(path)
  429.  
  430.     def clean(self):
  431.         """Delete old files in "tmp"."""
  432.         now = time.time()
  433.         for entry in os.listdir(os.path.join(self._path, 'tmp')):
  434.             path = os.path.join(self._path, 'tmp', entry)
  435.             if now - os.path.getatime(path) > 129600:   # 60 * 60 * 36
  436.                 os.remove(path)
  437.  
  438.     _count = 1  # This is used to generate unique file names.
  439.  
  440.     def _create_tmp(self):
  441.         """Create a file in the tmp subdirectory and open and return it."""
  442.         now = time.time()
  443.         hostname = socket.gethostname()
  444.         if '/' in hostname:
  445.             hostname = hostname.replace('/', r'\057')
  446.         if ':' in hostname:
  447.             hostname = hostname.replace(':', r'\072')
  448.         uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
  449.                                     Maildir._count, hostname)
  450.         path = os.path.join(self._path, 'tmp', uniq)
  451.         try:
  452.             os.stat(path)
  453.         except OSError, e:
  454.             if e.errno == errno.ENOENT:
  455.                 Maildir._count += 1
  456.                 try:
  457.                     return _create_carefully(path)
  458.                 except OSError, e:
  459.                     if e.errno != errno.EEXIST:
  460.                         raise
  461.             else:
  462.                 raise
  463.  
  464.         # Fall through to here if stat succeeded or open raised EEXIST.
  465.         raise ExternalClashError('Name clash prevented file creation: %s' %
  466.                                  path)
  467.  
  468.     def _refresh(self):
  469.         """Update table of contents mapping."""
  470.         self._toc = {}
  471.         for subdir in ('new', 'cur'):
  472.             subdir_path = os.path.join(self._path, subdir)
  473.             for entry in os.listdir(subdir_path):
  474.                 p = os.path.join(subdir_path, entry)
  475.                 if os.path.isdir(p):
  476.                     continue
  477.                 uniq = entry.split(self.colon)[0]
  478.                 self._toc[uniq] = os.path.join(subdir, entry)
  479.  
  480.     def _lookup(self, key):
  481.         """Use TOC to return subpath for given key, or raise a KeyError."""
  482.         try:
  483.             if os.path.exists(os.path.join(self._path, self._toc[key])):
  484.                 return self._toc[key]
  485.         except KeyError:
  486.             pass
  487.         self._refresh()
  488.         try:
  489.             return self._toc[key]
  490.         except KeyError:
  491.             raise KeyError('No message with key: %s' % key)
  492.  
  493.     # This method is for backward compatibility only.
  494.     def next(self):
  495.         """Return the next message in a one-time iteration."""
  496.         if not hasattr(self, '_onetime_keys'):
  497.             self._onetime_keys = self.iterkeys()
  498.         while True:
  499.             try:
  500.                 return self[self._onetime_keys.next()]
  501.             except StopIteration:
  502.                 return None
  503.             except KeyError:
  504.                 continue
  505.  
  506.  
  507. class _singlefileMailbox(Mailbox):
  508.     """A single-file mailbox."""
  509.  
  510.     def __init__(self, path, factory=None, create=True):
  511.         """Initialize a single-file mailbox."""
  512.         Mailbox.__init__(self, path, factory, create)
  513.         try:
  514.             f = open(self._path, 'rb+')
  515.         except IOError, e:
  516.             if e.errno == errno.ENOENT:
  517.                 if create:
  518.                     f = open(self._path, 'wb+')
  519.                 else:
  520.                     raise NoSuchMailboxError(self._path)
  521.             elif e.errno == errno.EACCES:
  522.                 f = open(self._path, 'rb')
  523.             else:
  524.                 raise
  525.         self._file = f
  526.         self._toc = None
  527.         self._next_key = 0
  528.         self._pending = False   # No changes require rewriting the file.
  529.         self._locked = False
  530.         self._file_length = None        # Used to record mailbox size
  531.  
  532.     def add(self, message):
  533.         """Add message and return assigned key."""
  534.         self._lookup()
  535.         self._toc[self._next_key] = self._append_message(message)
  536.         self._next_key += 1
  537.         self._pending = True
  538.         return self._next_key - 1
  539.  
  540.     def remove(self, key):
  541.         """Remove the keyed message; raise KeyError if it doesn't exist."""
  542.         self._lookup(key)
  543.         del self._toc[key]
  544.         self._pending = True
  545.  
  546.     def __setitem__(self, key, message):
  547.         """Replace the keyed message; raise KeyError if it doesn't exist."""
  548.         self._lookup(key)
  549.         self._toc[key] = self._append_message(message)
  550.         self._pending = True
  551.  
  552.     def iterkeys(self):
  553.         """Return an iterator over keys."""
  554.         self._lookup()
  555.         for key in self._toc.keys():
  556.             yield key
  557.  
  558.     def has_key(self, key):
  559.         """Return True if the keyed message exists, False otherwise."""
  560.         self._lookup()
  561.         return key in self._toc
  562.  
  563.     def __len__(self):
  564.         """Return a count of messages in the mailbox."""
  565.         self._lookup()
  566.         return len(self._toc)
  567.  
  568.     def lock(self):
  569.         """Lock the mailbox."""
  570.         if not self._locked:
  571.             _lock_file(self._file)
  572.             self._locked = True
  573.  
  574.     def unlock(self):
  575.         """Unlock the mailbox if it is locked."""
  576.         if self._locked:
  577.             _unlock_file(self._file)
  578.             self._locked = False
  579.  
  580.     def flush(self):
  581.         """Write any pending changes to disk."""
  582.         if not self._pending:
  583.             return
  584.  
  585.         # In order to be writing anything out at all, self._toc must
  586.         # already have been generated (and presumably has been modified
  587.         # by adding or deleting an item).
  588.         assert self._toc is not None
  589.  
  590.         # Check length of self._file; if it's changed, some other process
  591.         # has modified the mailbox since we scanned it.
  592.         self._file.seek(0, 2)
  593.         cur_len = self._file.tell()
  594.         if cur_len != self._file_length:
  595.             raise ExternalClashError('Size of mailbox file changed '
  596.                                      '(expected %i, found %i)' %
  597.                                      (self._file_length, cur_len))
  598.  
  599.         new_file = _create_temporary(self._path)
  600.         try:
  601.             new_toc = {}
  602.             self._pre_mailbox_hook(new_file)
  603.             for key in sorted(self._toc.keys()):
  604.                 start, stop = self._toc[key]
  605.                 self._file.seek(start)
  606.                 self._pre_message_hook(new_file)
  607.                 new_start = new_file.tell()
  608.                 while True:
  609.                     buffer = self._file.read(min(4096,
  610.                                                  stop - self._file.tell()))
  611.                     if buffer == '':
  612.                         break
  613.                     new_file.write(buffer)
  614.                 new_toc[key] = (new_start, new_file.tell())
  615.                 self._post_message_hook(new_file)
  616.         except:
  617.             new_file.close()
  618.             os.remove(new_file.name)
  619.             raise
  620.         _sync_close(new_file)
  621.         # self._file is about to get replaced, so no need to sync.
  622.         self._file.close()
  623.         try:
  624.             os.rename(new_file.name, self._path)
  625.         except OSError, e:
  626.             if e.errno == errno.EEXIST or \
  627.               (os.name == 'os2' and e.errno == errno.EACCES):
  628.                 os.remove(self._path)
  629.                 os.rename(new_file.name, self._path)
  630.             else:
  631.                 raise
  632.         self._file = open(self._path, 'rb+')
  633.         self._toc = new_toc
  634.         self._pending = False
  635.         if self._locked:
  636.             _lock_file(self._file, dotlock=False)
  637.  
  638.     def _pre_mailbox_hook(self, f):
  639.         """Called before writing the mailbox to file f."""
  640.         return
  641.  
  642.     def _pre_message_hook(self, f):
  643.         """Called before writing each message to file f."""
  644.         return
  645.  
  646.     def _post_message_hook(self, f):
  647.         """Called after writing each message to file f."""
  648.         return
  649.  
  650.     def close(self):
  651.         """Flush and close the mailbox."""
  652.         self.flush()
  653.         if self._locked:
  654.             self.unlock()
  655.         self._file.close()  # Sync has been done by self.flush() above.
  656.  
  657.     def _lookup(self, key=None):
  658.         """Return (start, stop) or raise KeyError."""
  659.         if self._toc is None:
  660.             self._generate_toc()
  661.         if key is not None:
  662.             try:
  663.                 return self._toc[key]
  664.             except KeyError:
  665.                 raise KeyError('No message with key: %s' % key)
  666.  
  667.     def _append_message(self, message):
  668.         """Append message to mailbox and return (start, stop) offsets."""
  669.         self._file.seek(0, 2)
  670.         self._pre_message_hook(self._file)
  671.         offsets = self._install_message(message)
  672.         self._post_message_hook(self._file)
  673.         self._file.flush()
  674.         self._file_length = self._file.tell()  # Record current length of mailbox
  675.         return offsets
  676.  
  677.  
  678.  
  679. class _mboxMMDF(_singlefileMailbox):
  680.     """An mbox or MMDF mailbox."""
  681.  
  682.     _mangle_from_ = True
  683.  
  684.     def get_message(self, key):
  685.         """Return a Message representation or raise a KeyError."""
  686.         start, stop = self._lookup(key)
  687.         self._file.seek(start)
  688.         from_line = self._file.readline().replace(os.linesep, '')
  689.         string = self._file.read(stop - self._file.tell())
  690.         msg = self._message_factory(string.replace(os.linesep, '\n'))
  691.         msg.set_from(from_line[5:])
  692.         return msg
  693.  
  694.     def get_string(self, key, from_=False):
  695.         """Return a string representation or raise a KeyError."""
  696.         start, stop = self._lookup(key)
  697.         self._file.seek(start)
  698.         if not from_:
  699.             self._file.readline()
  700.         string = self._file.read(stop - self._file.tell())
  701.         return string.replace(os.linesep, '\n')
  702.  
  703.     def get_file(self, key, from_=False):
  704.         """Return a file-like representation or raise a KeyError."""
  705.         start, stop = self._lookup(key)
  706.         self._file.seek(start)
  707.         if not from_:
  708.             self._file.readline()
  709.         return _PartialFile(self._file, self._file.tell(), stop)
  710.  
  711.     def _install_message(self, message):
  712.         """Format a message and blindly write to self._file."""
  713.         from_line = None
  714.         if isinstance(message, str) and message.startswith('From '):
  715.             newline = message.find('\n')
  716.             if newline != -1:
  717.                 from_line = message[:newline]
  718.                 message = message[newline + 1:]
  719.             else:
  720.                 from_line = message
  721.                 message = ''
  722.         elif isinstance(message, _mboxMMDFMessage):
  723.             from_line = 'From ' + message.get_from()
  724.         elif isinstance(message, email.message.Message):
  725.             from_line = message.get_unixfrom()  # May be None.
  726.         if from_line is None:
  727.             from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
  728.         start = self._file.tell()
  729.         self._file.write(from_line + os.linesep)
  730.         self._dump_message(message, self._file, self._mangle_from_)
  731.         stop = self._file.tell()
  732.         return (start, stop)
  733.  
  734.  
  735. class mbox(_mboxMMDF):
  736.     """A classic mbox mailbox."""
  737.  
  738.     _mangle_from_ = True
  739.  
  740.     def __init__(self, path, factory=None, create=True):
  741.         """Initialize an mbox mailbox."""
  742.         self._message_factory = mboxMessage
  743.         _mboxMMDF.__init__(self, path, factory, create)
  744.  
  745.     def _pre_message_hook(self, f):
  746.         """Called before writing each message to file f."""
  747.         if f.tell() != 0:
  748.             f.write(os.linesep)
  749.  
  750.     def _generate_toc(self):
  751.         """Generate key-to-(start, stop) table of contents."""
  752.         starts, stops = [], []
  753.         self._file.seek(0)
  754.         while True:
  755.             line_pos = self._file.tell()
  756.             line = self._file.readline()
  757.             if line.startswith('From '):
  758.                 if len(stops) < len(starts):
  759.                     stops.append(line_pos - len(os.linesep))
  760.                 starts.append(line_pos)
  761.             elif line == '':
  762.                 stops.append(line_pos)
  763.                 break
  764.         self._toc = dict(enumerate(zip(starts, stops)))
  765.         self._next_key = len(self._toc)
  766.         self._file_length = self._file.tell()
  767.  
  768.  
  769. class MMDF(_mboxMMDF):
  770.     """An MMDF mailbox."""
  771.  
  772.     def __init__(self, path, factory=None, create=True):
  773.         """Initialize an MMDF mailbox."""
  774.         self._message_factory = MMDFMessage
  775.         _mboxMMDF.__init__(self, path, factory, create)
  776.  
  777.     def _pre_message_hook(self, f):
  778.         """Called before writing each message to file f."""
  779.         f.write('\001\001\001\001' + os.linesep)
  780.  
  781.     def _post_message_hook(self, f):
  782.         """Called after writing each message to file f."""
  783.         f.write(os.linesep + '\001\001\001\001' + os.linesep)
  784.  
  785.     def _generate_toc(self):
  786.         """Generate key-to-(start, stop) table of contents."""
  787.         starts, stops = [], []
  788.         self._file.seek(0)
  789.         next_pos = 0
  790.         while True:
  791.             line_pos = next_pos
  792.             line = self._file.readline()
  793.             next_pos = self._file.tell()
  794.             if line.startswith('\001\001\001\001' + os.linesep):
  795.                 starts.append(next_pos)
  796.                 while True:
  797.                     line_pos = next_pos
  798.                     line = self._file.readline()
  799.                     next_pos = self._file.tell()
  800.                     if line == '\001\001\001\001' + os.linesep:
  801.                         stops.append(line_pos - len(os.linesep))
  802.                         break
  803.                     elif line == '':
  804.                         stops.append(line_pos)
  805.                         break
  806.             elif line == '':
  807.                 break
  808.         self._toc = dict(enumerate(zip(starts, stops)))
  809.         self._next_key = len(self._toc)
  810.         self._file.seek(0, 2)
  811.         self._file_length = self._file.tell()
  812.  
  813.  
  814. class MH(Mailbox):
  815.     """An MH mailbox."""
  816.  
  817.     def __init__(self, path, factory=None, create=True):
  818.         """Initialize an MH instance."""
  819.         Mailbox.__init__(self, path, factory, create)
  820.         if not os.path.exists(self._path):
  821.             if create:
  822.                 os.mkdir(self._path, 0700)
  823.                 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
  824.                                  os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
  825.             else:
  826.                 raise NoSuchMailboxError(self._path)
  827.         self._locked = False
  828.  
  829.     def add(self, message):
  830.         """Add message and return assigned key."""
  831.         keys = self.keys()
  832.         if len(keys) == 0:
  833.             new_key = 1
  834.         else:
  835.             new_key = max(keys) + 1
  836.         new_path = os.path.join(self._path, str(new_key))
  837.         f = _create_carefully(new_path)
  838.         try:
  839.             if self._locked:
  840.                 _lock_file(f)
  841.             try:
  842.                 self._dump_message(message, f)
  843.                 if isinstance(message, MHMessage):
  844.                     self._dump_sequences(message, new_key)
  845.             finally:
  846.                 if self._locked:
  847.                     _unlock_file(f)
  848.         finally:
  849.             _sync_close(f)
  850.         return new_key
  851.  
  852.     def remove(self, key):
  853.         """Remove the keyed message; raise KeyError if it doesn't exist."""
  854.         path = os.path.join(self._path, str(key))
  855.         try:
  856.             f = open(path, 'rb+')
  857.         except IOError, e:
  858.             if e.errno == errno.ENOENT:
  859.                 raise KeyError('No message with key: %s' % key)
  860.             else:
  861.                 raise
  862.         try:
  863.             if self._locked:
  864.                 _lock_file(f)
  865.             try:
  866.                 f.close()
  867.                 os.remove(os.path.join(self._path, str(key)))
  868.             finally:
  869.                 if self._locked:
  870.                     _unlock_file(f)
  871.         finally:
  872.             f.close()
  873.  
  874.     def __setitem__(self, key, message):
  875.         """Replace the keyed message; raise KeyError if it doesn't exist."""
  876.         path = os.path.join(self._path, str(key))
  877.         try:
  878.             f = open(path, 'rb+')
  879.         except IOError, e:
  880.             if e.errno == errno.ENOENT:
  881.                 raise KeyError('No message with key: %s' % key)
  882.             else:
  883.                 raise
  884.         try:
  885.             if self._locked:
  886.                 _lock_file(f)
  887.             try:
  888.                 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
  889.                 self._dump_message(message, f)
  890.                 if isinstance(message, MHMessage):
  891.                     self._dump_sequences(message, key)
  892.             finally:
  893.                 if self._locked:
  894.                     _unlock_file(f)
  895.         finally:
  896.             _sync_close(f)
  897.  
  898.     def get_message(self, key):
  899.         """Return a Message representation or raise a KeyError."""
  900.         try:
  901.             if self._locked:
  902.                 f = open(os.path.join(self._path, str(key)), 'r+')
  903.             else:
  904.                 f = open(os.path.join(self._path, str(key)), 'r')
  905.         except IOError, e:
  906.             if e.errno == errno.ENOENT:
  907.                 raise KeyError('No message with key: %s' % key)
  908.             else:
  909.                 raise
  910.         try:
  911.             if self._locked:
  912.                 _lock_file(f)
  913.             try:
  914.                 msg = MHMessage(f)
  915.             finally:
  916.                 if self._locked:
  917.                     _unlock_file(f)
  918.         finally:
  919.             f.close()
  920.         for name, key_list in self.get_sequences().iteritems():
  921.             if key in key_list:
  922.                 msg.add_sequence(name)
  923.         return msg
  924.  
  925.     def get_string(self, key):
  926.         """Return a string representation or raise a KeyError."""
  927.         try:
  928.             if self._locked:
  929.                 f = open(os.path.join(self._path, str(key)), 'r+')
  930.             else:
  931.                 f = open(os.path.join(self._path, str(key)), 'r')
  932.         except IOError, e:
  933.             if e.errno == errno.ENOENT:
  934.                 raise KeyError('No message with key: %s' % key)
  935.             else:
  936.                 raise
  937.         try:
  938.             if self._locked:
  939.                 _lock_file(f)
  940.             try:
  941.                 return f.read()
  942.             finally:
  943.                 if self._locked:
  944.                     _unlock_file(f)
  945.         finally:
  946.             f.close()
  947.  
  948.     def get_file(self, key):
  949.         """Return a file-like representation or raise a KeyError."""
  950.         try:
  951.             f = open(os.path.join(self._path, str(key)), 'rb')
  952.         except IOError, e:
  953.             if e.errno == errno.ENOENT:
  954.                 raise KeyError('No message with key: %s' % key)
  955.             else:
  956.                 raise
  957.         return _ProxyFile(f)
  958.  
  959.     def iterkeys(self):
  960.         """Return an iterator over keys."""
  961.         return iter(sorted(int(entry) for entry in os.listdir(self._path)
  962.                                       if entry.isdigit()))
  963.  
  964.     def has_key(self, key):
  965.         """Return True if the keyed message exists, False otherwise."""
  966.         return os.path.exists(os.path.join(self._path, str(key)))
  967.  
  968.     def __len__(self):
  969.         """Return a count of messages in the mailbox."""
  970.         return len(list(self.iterkeys()))
  971.  
  972.     def lock(self):
  973.         """Lock the mailbox."""
  974.         if not self._locked:
  975.             self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
  976.             _lock_file(self._file)
  977.             self._locked = True
  978.  
  979.     def unlock(self):
  980.         """Unlock the mailbox if it is locked."""
  981.         if self._locked:
  982.             _unlock_file(self._file)
  983.             _sync_close(self._file)
  984.             del self._file
  985.             self._locked = False
  986.  
  987.     def flush(self):
  988.         """Write any pending changes to the disk."""
  989.         return
  990.  
  991.     def close(self):
  992.         """Flush and close the mailbox."""
  993.         if self._locked:
  994.             self.unlock()
  995.  
  996.     def list_folders(self):
  997.         """Return a list of folder names."""
  998.         result = []
  999.         for entry in os.listdir(self._path):
  1000.             if os.path.isdir(os.path.join(self._path, entry)):
  1001.                 result.append(entry)
  1002.         return result
  1003.  
  1004.     def get_folder(self, folder):
  1005.         """Return an MH instance for the named folder."""
  1006.         return MH(os.path.join(self._path, folder),
  1007.                   factory=self._factory, create=False)
  1008.  
  1009.     def add_folder(self, folder):
  1010.         """Create a folder and return an MH instance representing it."""
  1011.         return MH(os.path.join(self._path, folder),
  1012.                   factory=self._factory)
  1013.  
  1014.     def remove_folder(self, folder):
  1015.         """Delete the named folder, which must be empty."""
  1016.         path = os.path.join(self._path, folder)
  1017.         entries = os.listdir(path)
  1018.         if entries == ['.mh_sequences']:
  1019.             os.remove(os.path.join(path, '.mh_sequences'))
  1020.         elif entries == []:
  1021.             pass
  1022.         else:
  1023.             raise NotEmptyError('Folder not empty: %s' % self._path)
  1024.         os.rmdir(path)
  1025.  
  1026.     def get_sequences(self):
  1027.         """Return a name-to-key-list dictionary to define each sequence."""
  1028.         results = {}
  1029.         f = open(os.path.join(self._path, '.mh_sequences'), 'r')
  1030.         try:
  1031.             all_keys = set(self.keys())
  1032.             for line in f:
  1033.                 try:
  1034.                     name, contents = line.split(':')
  1035.                     keys = set()
  1036.                     for spec in contents.split():
  1037.                         if spec.isdigit():
  1038.                             keys.add(int(spec))
  1039.                         else:
  1040.                             start, stop = (int(x) for x in spec.split('-'))
  1041.                             keys.update(range(start, stop + 1))
  1042.                     results[name] = [key for key in sorted(keys) \
  1043.                                          if key in all_keys]
  1044.                     if len(results[name]) == 0:
  1045.                         del results[name]
  1046.                 except ValueError:
  1047.                     raise FormatError('Invalid sequence specification: %s' %
  1048.                                       line.rstrip())
  1049.         finally:
  1050.             f.close()
  1051.         return results
  1052.  
  1053.     def set_sequences(self, sequences):
  1054.         """Set sequences using the given name-to-key-list dictionary."""
  1055.         f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
  1056.         try:
  1057.             os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
  1058.             for name, keys in sequences.iteritems():
  1059.                 if len(keys) == 0:
  1060.                     continue
  1061.                 f.write('%s:' % name)
  1062.                 prev = None
  1063.                 completing = False
  1064.                 for key in sorted(set(keys)):
  1065.                     if key - 1 == prev:
  1066.                         if not completing:
  1067.                             completing = True
  1068.                             f.write('-')
  1069.                     elif completing:
  1070.                         completing = False
  1071.                         f.write('%s %s' % (prev, key))
  1072.                     else:
  1073.                         f.write(' %s' % key)
  1074.                     prev = key
  1075.                 if completing:
  1076.                     f.write(str(prev) + '\n')
  1077.                 else:
  1078.                     f.write('\n')
  1079.         finally:
  1080.             _sync_close(f)
  1081.  
  1082.     def pack(self):
  1083.         """Re-name messages to eliminate numbering gaps. Invalidates keys."""
  1084.         sequences = self.get_sequences()
  1085.         prev = 0
  1086.         changes = []
  1087.         for key in self.iterkeys():
  1088.             if key - 1 != prev:
  1089.                 changes.append((key, prev + 1))
  1090.                 if hasattr(os, 'link'):
  1091.                     os.link(os.path.join(self._path, str(key)),
  1092.                             os.path.join(self._path, str(prev + 1)))
  1093.                     os.unlink(os.path.join(self._path, str(key)))
  1094.                 else:
  1095.                     os.rename(os.path.join(self._path, str(key)),
  1096.                               os.path.join(self._path, str(prev + 1)))
  1097.             prev += 1
  1098.         self._next_key = prev + 1
  1099.         if len(changes) == 0:
  1100.             return
  1101.         for name, key_list in sequences.items():
  1102.             for old, new in changes:
  1103.                 if old in key_list:
  1104.                     key_list[key_list.index(old)] = new
  1105.         self.set_sequences(sequences)
  1106.  
  1107.     def _dump_sequences(self, message, key):
  1108.         """Inspect a new MHMessage and update sequences appropriately."""
  1109.         pending_sequences = message.get_sequences()
  1110.         all_sequences = self.get_sequences()
  1111.         for name, key_list in all_sequences.iteritems():
  1112.             if name in pending_sequences:
  1113.                 key_list.append(key)
  1114.             elif key in key_list:
  1115.                 del key_list[key_list.index(key)]
  1116.         for sequence in pending_sequences:
  1117.             if sequence not in all_sequences:
  1118.                 all_sequences[sequence] = [key]
  1119.         self.set_sequences(all_sequences)
  1120.  
  1121.  
  1122. class Babyl(_singlefileMailbox):
  1123.     """An Rmail-style Babyl mailbox."""
  1124.  
  1125.     _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
  1126.                                  'forwarded', 'edited', 'resent'))
  1127.  
  1128.     def __init__(self, path, factory=None, create=True):
  1129.         """Initialize a Babyl mailbox."""
  1130.         _singlefileMailbox.__init__(self, path, factory, create)
  1131.         self._labels = {}
  1132.  
  1133.     def add(self, message):
  1134.         """Add message and return assigned key."""
  1135.         key = _singlefileMailbox.add(self, message)
  1136.         if isinstance(message, BabylMessage):
  1137.             self._labels[key] = message.get_labels()
  1138.         return key
  1139.  
  1140.     def remove(self, key):
  1141.         """Remove the keyed message; raise KeyError if it doesn't exist."""
  1142.         _singlefileMailbox.remove(self, key)
  1143.         if key in self._labels:
  1144.             del self._labels[key]
  1145.  
  1146.     def __setitem__(self, key, message):
  1147.         """Replace the keyed message; raise KeyError if it doesn't exist."""
  1148.         _singlefileMailbox.__setitem__(self, key, message)
  1149.         if isinstance(message, BabylMessage):
  1150.             self._labels[key] = message.get_labels()
  1151.  
  1152.     def get_message(self, key):
  1153.         """Return a Message representation or raise a KeyError."""
  1154.         start, stop = self._lookup(key)
  1155.         self._file.seek(start)
  1156.         self._file.readline()   # Skip '1,' line specifying labels.
  1157.         original_headers = StringIO.StringIO()
  1158.         while True:
  1159.             line = self._file.readline()
  1160.             if line == '*** EOOH ***' + os.linesep or line == '':
  1161.                 break
  1162.             original_headers.write(line.replace(os.linesep, '\n'))
  1163.         visible_headers = StringIO.StringIO()
  1164.         while True:
  1165.             line = self._file.readline()
  1166.             if line == os.linesep or line == '':
  1167.                 break
  1168.             visible_headers.write(line.replace(os.linesep, '\n'))
  1169.         body = self._file.read(stop - self._file.tell()).replace(os.linesep,
  1170.                                                                  '\n')
  1171.         msg = BabylMessage(original_headers.getvalue() + body)
  1172.         msg.set_visible(visible_headers.getvalue())
  1173.         if key in self._labels:
  1174.             msg.set_labels(self._labels[key])
  1175.         return msg
  1176.  
  1177.     def get_string(self, key):
  1178.         """Return a string representation or raise a KeyError."""
  1179.         start, stop = self._lookup(key)
  1180.         self._file.seek(start)
  1181.         self._file.readline()   # Skip '1,' line specifying labels.
  1182.         original_headers = StringIO.StringIO()
  1183.         while True:
  1184.             line = self._file.readline()
  1185.             if line == '*** EOOH ***' + os.linesep or line == '':
  1186.                 break
  1187.             original_headers.write(line.replace(os.linesep, '\n'))
  1188.         while True:
  1189.             line = self._file.readline()
  1190.             if line == os.linesep or line == '':
  1191.                 break
  1192.         return original_headers.getvalue() + \
  1193.                self._file.read(stop - self._file.tell()).replace(os.linesep,
  1194.                                                                  '\n')
  1195.  
  1196.     def get_file(self, key):
  1197.         """Return a file-like representation or raise a KeyError."""
  1198.         return StringIO.StringIO(self.get_string(key).replace('\n',
  1199.                                                               os.linesep))
  1200.  
  1201.     def get_labels(self):
  1202.         """Return a list of user-defined labels in the mailbox."""
  1203.         self._lookup()
  1204.         labels = set()
  1205.         for label_list in self._labels.values():
  1206.             labels.update(label_list)
  1207.         labels.difference_update(self._special_labels)
  1208.         return list(labels)
  1209.  
  1210.     def _generate_toc(self):
  1211.         """Generate key-to-(start, stop) table of contents."""
  1212.         starts, stops = [], []
  1213.         self._file.seek(0)
  1214.         next_pos = 0
  1215.         label_lists = []
  1216.         while True:
  1217.             line_pos = next_pos
  1218.             line = self._file.readline()
  1219.             next_pos = self._file.tell()
  1220.             if line == '\037\014' + os.linesep:
  1221.                 if len(stops) < len(starts):
  1222.                     stops.append(line_pos - len(os.linesep))
  1223.                 starts.append(next_pos)
  1224.                 labels = [label.strip() for label
  1225.                                         in self._file.readline()[1:].split(',')
  1226.                                         if label.strip() != '']
  1227.                 label_lists.append(labels)
  1228.             elif line == '\037' or line == '\037' + os.linesep:
  1229.                 if len(stops) < len(starts):
  1230.                     stops.append(line_pos - len(os.linesep))
  1231.             elif line == '':
  1232.                 stops.append(line_pos - len(os.linesep))
  1233.                 break
  1234.         self._toc = dict(enumerate(zip(starts, stops)))
  1235.         self._labels = dict(enumerate(label_lists))
  1236.         self._next_key = len(self._toc)
  1237.         self._file.seek(0, 2)
  1238.         self._file_length = self._file.tell()
  1239.  
  1240.     def _pre_mailbox_hook(self, f):
  1241.         """Called before writing the mailbox to file f."""
  1242.         f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
  1243.                 (os.linesep, os.linesep, ','.join(self.get_labels()),
  1244.                  os.linesep))
  1245.  
  1246.     def _pre_message_hook(self, f):
  1247.         """Called before writing each message to file f."""
  1248.         f.write('\014' + os.linesep)
  1249.  
  1250.     def _post_message_hook(self, f):
  1251.         """Called after writing each message to file f."""
  1252.         f.write(os.linesep + '\037')
  1253.  
  1254.     def _install_message(self, message):
  1255.         """Write message contents and return (start, stop)."""
  1256.         start = self._file.tell()
  1257.         if isinstance(message, BabylMessage):
  1258.             special_labels = []
  1259.             labels = []
  1260.             for label in message.get_labels():
  1261.                 if label in self._special_labels:
  1262.                     special_labels.append(label)
  1263.                 else:
  1264.                     labels.append(label)
  1265.             self._file.write('1')
  1266.             for label in special_labels:
  1267.                 self._file.write(', ' + label)
  1268.             self._file.write(',,')
  1269.             for label in labels:
  1270.                 self._file.write(' ' + label + ',')
  1271.             self._file.write(os.linesep)
  1272.         else:
  1273.             self._file.write('1,,' + os.linesep)
  1274.         if isinstance(message, email.message.Message):
  1275.             orig_buffer = StringIO.StringIO()
  1276.             orig_generator = email.generator.Generator(orig_buffer, False, 0)
  1277.             orig_generator.flatten(message)
  1278.             orig_buffer.seek(0)
  1279.             while True:
  1280.                 line = orig_buffer.readline()
  1281.                 self._file.write(line.replace('\n', os.linesep))
  1282.                 if line == '\n' or line == '':
  1283.                     break
  1284.             self._file.write('*** EOOH ***' + os.linesep)
  1285.             if isinstance(message, BabylMessage):
  1286.                 vis_buffer = StringIO.StringIO()
  1287.                 vis_generator = email.generator.Generator(vis_buffer, False, 0)
  1288.                 vis_generator.flatten(message.get_visible())
  1289.                 while True:
  1290.                     line = vis_buffer.readline()
  1291.                     self._file.write(line.replace('\n', os.linesep))
  1292.                     if line == '\n' or line == '':
  1293.                         break
  1294.             else:
  1295.                 orig_buffer.seek(0)
  1296.                 while True:
  1297.                     line = orig_buffer.readline()
  1298.                     self._file.write(line.replace('\n', os.linesep))
  1299.                     if line == '\n' or line == '':
  1300.                         break
  1301.             while True:
  1302.                 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
  1303.                 if buffer == '':
  1304.                     break
  1305.                 self._file.write(buffer.replace('\n', os.linesep))
  1306.         elif isinstance(message, str):
  1307.             body_start = message.find('\n\n') + 2
  1308.             if body_start - 2 != -1:
  1309.                 self._file.write(message[:body_start].replace('\n',
  1310.                                                               os.linesep))
  1311.                 self._file.write('*** EOOH ***' + os.linesep)
  1312.                 self._file.write(message[:body_start].replace('\n',
  1313.                                                               os.linesep))
  1314.                 self._file.write(message[body_start:].replace('\n',
  1315.                                                               os.linesep))
  1316.             else:
  1317.                 self._file.write('*** EOOH ***' + os.linesep + os.linesep)
  1318.                 self._file.write(message.replace('\n', os.linesep))
  1319.         elif hasattr(message, 'readline'):
  1320.             original_pos = message.tell()
  1321.             first_pass = True
  1322.             while True:
  1323.                 line = message.readline()
  1324.                 self._file.write(line.replace('\n', os.linesep))
  1325.                 if line == '\n' or line == '':
  1326.                     self._file.write('*** EOOH ***' + os.linesep)
  1327.                     if first_pass:
  1328.                         first_pass = False
  1329.                         message.seek(original_pos)
  1330.                     else:
  1331.                         break
  1332.             while True:
  1333.                 buffer = message.read(4096)     # Buffer size is arbitrary.
  1334.                 if buffer == '':
  1335.                     break
  1336.                 self._file.write(buffer.replace('\n', os.linesep))
  1337.         else:
  1338.             raise TypeError('Invalid message type: %s' % type(message))
  1339.         stop = self._file.tell()
  1340.         return (start, stop)
  1341.  
  1342.  
  1343. class Message(email.message.Message):
  1344.     """Message with mailbox-format-specific properties."""
  1345.  
  1346.     def __init__(self, message=None):
  1347.         """Initialize a Message instance."""
  1348.         if isinstance(message, email.message.Message):
  1349.             self._become_message(copy.deepcopy(message))
  1350.             if isinstance(message, Message):
  1351.                 message._explain_to(self)
  1352.         elif isinstance(message, str):
  1353.             self._become_message(email.message_from_string(message))
  1354.         elif hasattr(message, "read"):
  1355.             self._become_message(email.message_from_file(message))
  1356.         elif message is None:
  1357.             email.message.Message.__init__(self)
  1358.         else:
  1359.             raise TypeError('Invalid message type: %s' % type(message))
  1360.  
  1361.     def _become_message(self, message):
  1362.         """Assume the non-format-specific state of message."""
  1363.         for name in ('_headers', '_unixfrom', '_payload', '_charset',
  1364.                      'preamble', 'epilogue', 'defects', '_default_type'):
  1365.             self.__dict__[name] = message.__dict__[name]
  1366.  
  1367.     def _explain_to(self, message):
  1368.         """Copy format-specific state to message insofar as possible."""
  1369.         if isinstance(message, Message):
  1370.             return  # There's nothing format-specific to explain.
  1371.         else:
  1372.             raise TypeError('Cannot convert to specified type')
  1373.  
  1374.  
  1375. class MaildirMessage(Message):
  1376.     """Message with Maildir-specific properties."""
  1377.  
  1378.     def __init__(self, message=None):
  1379.         """Initialize a MaildirMessage instance."""
  1380.         self._subdir = 'new'
  1381.         self._info = ''
  1382.         self._date = time.time()
  1383.         Message.__init__(self, message)
  1384.  
  1385.     def get_subdir(self):
  1386.         """Return 'new' or 'cur'."""
  1387.         return self._subdir
  1388.  
  1389.     def set_subdir(self, subdir):
  1390.         """Set subdir to 'new' or 'cur'."""
  1391.         if subdir == 'new' or subdir == 'cur':
  1392.             self._subdir = subdir
  1393.         else:
  1394.             raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
  1395.  
  1396.     def get_flags(self):
  1397.         """Return as a string the flags that are set."""
  1398.         if self._info.startswith('2,'):
  1399.             return self._info[2:]
  1400.         else:
  1401.             return ''
  1402.  
  1403.     def set_flags(self, flags):
  1404.         """Set the given flags and unset all others."""
  1405.         self._info = '2,' + ''.join(sorted(flags))
  1406.  
  1407.     def add_flag(self, flag):
  1408.         """Set the given flag(s) without changing others."""
  1409.         self.set_flags(''.join(set(self.get_flags()) | set(flag)))
  1410.  
  1411.     def remove_flag(self, flag):
  1412.         """Unset the given string flag(s) without changing others."""
  1413.         if self.get_flags() != '':
  1414.             self.set_flags(''.join(set(self.get_flags()) - set(flag)))
  1415.  
  1416.     def get_date(self):
  1417.         """Return delivery date of message, in seconds since the epoch."""
  1418.         return self._date
  1419.  
  1420.     def set_date(self, date):
  1421.         """Set delivery date of message, in seconds since the epoch."""
  1422.         try:
  1423.             self._date = float(date)
  1424.         except ValueError:
  1425.             raise TypeError("can't convert to float: %s" % date)
  1426.  
  1427.     def get_info(self):
  1428.         """Get the message's "info" as a string."""
  1429.         return self._info
  1430.  
  1431.     def set_info(self, info):
  1432.         """Set the message's "info" string."""
  1433.         if isinstance(info, str):
  1434.             self._info = info
  1435.         else:
  1436.             raise TypeError('info must be a string: %s' % type(info))
  1437.  
  1438.     def _explain_to(self, message):
  1439.         """Copy Maildir-specific state to message insofar as possible."""
  1440.         if isinstance(message, MaildirMessage):
  1441.             message.set_flags(self.get_flags())
  1442.             message.set_subdir(self.get_subdir())
  1443.             message.set_date(self.get_date())
  1444.         elif isinstance(message, _mboxMMDFMessage):
  1445.             flags = set(self.get_flags())
  1446.             if 'S' in flags:
  1447.                 message.add_flag('R')
  1448.             if self.get_subdir() == 'cur':
  1449.                 message.add_flag('O')
  1450.             if 'T' in flags:
  1451.                 message.add_flag('D')
  1452.             if 'F' in flags:
  1453.                 message.add_flag('F')
  1454.             if 'R' in flags:
  1455.                 message.add_flag('A')
  1456.             message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
  1457.         elif isinstance(message, MHMessage):
  1458.             flags = set(self.get_flags())
  1459.             if 'S' not in flags:
  1460.                 message.add_sequence('unseen')
  1461.             if 'R' in flags:
  1462.                 message.add_sequence('replied')
  1463.             if 'F' in flags:
  1464.                 message.add_sequence('flagged')
  1465.         elif isinstance(message, BabylMessage):
  1466.             flags = set(self.get_flags())
  1467.             if 'S' not in flags:
  1468.                 message.add_label('unseen')
  1469.             if 'T' in flags:
  1470.                 message.add_label('deleted')
  1471.             if 'R' in flags:
  1472.                 message.add_label('answered')
  1473.             if 'P' in flags:
  1474.                 message.add_label('forwarded')
  1475.         elif isinstance(message, Message):
  1476.             pass
  1477.         else:
  1478.             raise TypeError('Cannot convert to specified type: %s' %
  1479.                             type(message))
  1480.  
  1481.  
  1482. class _mboxMMDFMessage(Message):
  1483.     """Message with mbox- or MMDF-specific properties."""
  1484.  
  1485.     def __init__(self, message=None):
  1486.         """Initialize an mboxMMDFMessage instance."""
  1487.         self.set_from('MAILER-DAEMON', True)
  1488.         if isinstance(message, email.message.Message):
  1489.             unixfrom = message.get_unixfrom()
  1490.             if unixfrom is not None and unixfrom.startswith('From '):
  1491.                 self.set_from(unixfrom[5:])
  1492.         Message.__init__(self, message)
  1493.  
  1494.     def get_from(self):
  1495.         """Return contents of "From " line."""
  1496.         return self._from
  1497.  
  1498.     def set_from(self, from_, time_=None):
  1499.         """Set "From " line, formatting and appending time_ if specified."""
  1500.         if time_ is not None:
  1501.             if time_ is True:
  1502.                 time_ = time.gmtime()
  1503.             from_ += ' ' + time.asctime(time_)
  1504.         self._from = from_
  1505.  
  1506.     def get_flags(self):
  1507.         """Return as a string the flags that are set."""
  1508.         return self.get('Status', '') + self.get('X-Status', '')
  1509.  
  1510.     def set_flags(self, flags):
  1511.         """Set the given flags and unset all others."""
  1512.         flags = set(flags)
  1513.         status_flags, xstatus_flags = '', ''
  1514.         for flag in ('R', 'O'):
  1515.             if flag in flags:
  1516.                 status_flags += flag
  1517.                 flags.remove(flag)
  1518.         for flag in ('D', 'F', 'A'):
  1519.             if flag in flags:
  1520.                 xstatus_flags += flag
  1521.                 flags.remove(flag)
  1522.         xstatus_flags += ''.join(sorted(flags))
  1523.         try:
  1524.             self.replace_header('Status', status_flags)
  1525.         except KeyError:
  1526.             self.add_header('Status', status_flags)
  1527.         try:
  1528.             self.replace_header('X-Status', xstatus_flags)
  1529.         except KeyError:
  1530.             self.add_header('X-Status', xstatus_flags)
  1531.  
  1532.     def add_flag(self, flag):
  1533.         """Set the given flag(s) without changing others."""
  1534.         self.set_flags(''.join(set(self.get_flags()) | set(flag)))
  1535.  
  1536.     def remove_flag(self, flag):
  1537.         """Unset the given string flag(s) without changing others."""
  1538.         if 'Status' in self or 'X-Status' in self:
  1539.             self.set_flags(''.join(set(self.get_flags()) - set(flag)))
  1540.  
  1541.     def _explain_to(self, message):
  1542.         """Copy mbox- or MMDF-specific state to message insofar as possible."""
  1543.         if isinstance(message, MaildirMessage):
  1544.             flags = set(self.get_flags())
  1545.             if 'O' in flags:
  1546.                 message.set_subdir('cur')
  1547.             if 'F' in flags:
  1548.                 message.add_flag('F')
  1549.             if 'A' in flags:
  1550.                 message.add_flag('R')
  1551.             if 'R' in flags:
  1552.                 message.add_flag('S')
  1553.             if 'D' in flags:
  1554.                 message.add_flag('T')
  1555.             del message['status']
  1556.             del message['x-status']
  1557.             maybe_date = ' '.join(self.get_from().split()[-5:])
  1558.             try:
  1559.                 message.set_date(calendar.timegm(time.strptime(maybe_date,
  1560.                                                       '%a %b %d %H:%M:%S %Y')))
  1561.             except (ValueError, OverflowError):
  1562.                 pass
  1563.         elif isinstance(message, _mboxMMDFMessage):
  1564.             message.set_flags(self.get_flags())
  1565.             message.set_from(self.get_from())
  1566.         elif isinstance(message, MHMessage):
  1567.             flags = set(self.get_flags())
  1568.             if 'R' not in flags:
  1569.                 message.add_sequence('unseen')
  1570.             if 'A' in flags:
  1571.                 message.add_sequence('replied')
  1572.             if 'F' in flags:
  1573.                 message.add_sequence('flagged')
  1574.             del message['status']
  1575.             del message['x-status']
  1576.         elif isinstance(message, BabylMessage):
  1577.             flags = set(self.get_flags())
  1578.             if 'R' not in flags:
  1579.                 message.add_label('unseen')
  1580.             if 'D' in flags:
  1581.                 message.add_label('deleted')
  1582.             if 'A' in flags:
  1583.                 message.add_label('answered')
  1584.             del message['status']
  1585.             del message['x-status']
  1586.         elif isinstance(message, Message):
  1587.             pass
  1588.         else:
  1589.             raise TypeError('Cannot convert to specified type: %s' %
  1590.                             type(message))
  1591.  
  1592.  
  1593. class mboxMessage(_mboxMMDFMessage):
  1594.     """Message with mbox-specific properties."""
  1595.  
  1596.  
  1597. class MHMessage(Message):
  1598.     """Message with MH-specific properties."""
  1599.  
  1600.     def __init__(self, message=None):
  1601.         """Initialize an MHMessage instance."""
  1602.         self._sequences = []
  1603.         Message.__init__(self, message)
  1604.  
  1605.     def get_sequences(self):
  1606.         """Return a list of sequences that include the message."""
  1607.         return self._sequences[:]
  1608.  
  1609.     def set_sequences(self, sequences):
  1610.         """Set the list of sequences that include the message."""
  1611.         self._sequences = list(sequences)
  1612.  
  1613.     def add_sequence(self, sequence):
  1614.         """Add sequence to list of sequences including the message."""
  1615.         if isinstance(sequence, str):
  1616.             if not sequence in self._sequences:
  1617.                 self._sequences.append(sequence)
  1618.         else:
  1619.             raise TypeError('sequence must be a string: %s' % type(sequence))
  1620.  
  1621.     def remove_sequence(self, sequence):
  1622.         """Remove sequence from the list of sequences including the message."""
  1623.         try:
  1624.             self._sequences.remove(sequence)
  1625.         except ValueError:
  1626.             pass
  1627.  
  1628.     def _explain_to(self, message):
  1629.         """Copy MH-specific state to message insofar as possible."""
  1630.         if isinstance(message, MaildirMessage):
  1631.             sequences = set(self.get_sequences())
  1632.             if 'unseen' in sequences:
  1633.                 message.set_subdir('cur')
  1634.             else:
  1635.                 message.set_subdir('cur')
  1636.                 message.add_flag('S')
  1637.             if 'flagged' in sequences:
  1638.                 message.add_flag('F')
  1639.             if 'replied' in sequences:
  1640.                 message.add_flag('R')
  1641.         elif isinstance(message, _mboxMMDFMessage):
  1642.             sequences = set(self.get_sequences())
  1643.             if 'unseen' not in sequences:
  1644.                 message.add_flag('RO')
  1645.             else:
  1646.                 message.add_flag('O')
  1647.             if 'flagged' in sequences:
  1648.                 message.add_flag('F')
  1649.             if 'replied' in sequences:
  1650.                 message.add_flag('A')
  1651.         elif isinstance(message, MHMessage):
  1652.             for sequence in self.get_sequences():
  1653.                 message.add_sequence(sequence)
  1654.         elif isinstance(message, BabylMessage):
  1655.             sequences = set(self.get_sequences())
  1656.             if 'unseen' in sequences:
  1657.                 message.add_label('unseen')
  1658.             if 'replied' in sequences:
  1659.                 message.add_label('answered')
  1660.         elif isinstance(message, Message):
  1661.             pass
  1662.         else:
  1663.             raise TypeError('Cannot convert to specified type: %s' %
  1664.                             type(message))
  1665.  
  1666.  
  1667. class BabylMessage(Message):
  1668.     """Message with Babyl-specific properties."""
  1669.  
  1670.     def __init__(self, message=None):
  1671.         """Initialize an BabylMessage instance."""
  1672.         self._labels = []
  1673.         self._visible = Message()
  1674.         Message.__init__(self, message)
  1675.  
  1676.     def get_labels(self):
  1677.         """Return a list of labels on the message."""
  1678.         return self._labels[:]
  1679.  
  1680.     def set_labels(self, labels):
  1681.         """Set the list of labels on the message."""
  1682.         self._labels = list(labels)
  1683.  
  1684.     def add_label(self, label):
  1685.         """Add label to list of labels on the message."""
  1686.         if isinstance(label, str):
  1687.             if label not in self._labels:
  1688.                 self._labels.append(label)
  1689.         else:
  1690.             raise TypeError('label must be a string: %s' % type(label))
  1691.  
  1692.     def remove_label(self, label):
  1693.         """Remove label from the list of labels on the message."""
  1694.         try:
  1695.             self._labels.remove(label)
  1696.         except ValueError:
  1697.             pass
  1698.  
  1699.     def get_visible(self):
  1700.         """Return a Message representation of visible headers."""
  1701.         return Message(self._visible)
  1702.  
  1703.     def set_visible(self, visible):
  1704.         """Set the Message representation of visible headers."""
  1705.         self._visible = Message(visible)
  1706.  
  1707.     def update_visible(self):
  1708.         """Update and/or sensibly generate a set of visible headers."""
  1709.         for header in self._visible.keys():
  1710.             if header in self:
  1711.                 self._visible.replace_header(header, self[header])
  1712.             else:
  1713.                 del self._visible[header]
  1714.         for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
  1715.             if header in self and header not in self._visible:
  1716.                 self._visible[header] = self[header]
  1717.  
  1718.     def _explain_to(self, message):
  1719.         """Copy Babyl-specific state to message insofar as possible."""
  1720.         if isinstance(message, MaildirMessage):
  1721.             labels = set(self.get_labels())
  1722.             if 'unseen' in labels:
  1723.                 message.set_subdir('cur')
  1724.             else:
  1725.                 message.set_subdir('cur')
  1726.                 message.add_flag('S')
  1727.             if 'forwarded' in labels or 'resent' in labels:
  1728.                 message.add_flag('P')
  1729.             if 'answered' in labels:
  1730.                 message.add_flag('R')
  1731.             if 'deleted' in labels:
  1732.                 message.add_flag('T')
  1733.         elif isinstance(message, _mboxMMDFMessage):
  1734.             labels = set(self.get_labels())
  1735.             if 'unseen' not in labels:
  1736.                 message.add_flag('RO')
  1737.             else:
  1738.                 message.add_flag('O')
  1739.             if 'deleted' in labels:
  1740.                 message.add_flag('D')
  1741.             if 'answered' in labels:
  1742.                 message.add_flag('A')
  1743.         elif isinstance(message, MHMessage):
  1744.             labels = set(self.get_labels())
  1745.             if 'unseen' in labels:
  1746.                 message.add_sequence('unseen')
  1747.             if 'answered' in labels:
  1748.                 message.add_sequence('replied')
  1749.         elif isinstance(message, BabylMessage):
  1750.             message.set_visible(self.get_visible())
  1751.             for label in self.get_labels():
  1752.                 message.add_label(label)
  1753.         elif isinstance(message, Message):
  1754.             pass
  1755.         else:
  1756.             raise TypeError('Cannot convert to specified type: %s' %
  1757.                             type(message))
  1758.  
  1759.  
  1760. class MMDFMessage(_mboxMMDFMessage):
  1761.     """Message with MMDF-specific properties."""
  1762.  
  1763.  
  1764. class _ProxyFile:
  1765.     """A read-only wrapper of a file."""
  1766.  
  1767.     def __init__(self, f, pos=None):
  1768.         """Initialize a _ProxyFile."""
  1769.         self._file = f
  1770.         if pos is None:
  1771.             self._pos = f.tell()
  1772.         else:
  1773.             self._pos = pos
  1774.  
  1775.     def read(self, size=None):
  1776.         """Read bytes."""
  1777.         return self._read(size, self._file.read)
  1778.  
  1779.     def readline(self, size=None):
  1780.         """Read a line."""
  1781.         return self._read(size, self._file.readline)
  1782.  
  1783.     def readlines(self, sizehint=None):
  1784.         """Read multiple lines."""
  1785.         result = []
  1786.         for line in self:
  1787.             result.append(line)
  1788.             if sizehint is not None:
  1789.                 sizehint -= len(line)
  1790.                 if sizehint <= 0:
  1791.                     break
  1792.         return result
  1793.  
  1794.     def __iter__(self):
  1795.         """Iterate over lines."""
  1796.         return iter(self.readline, "")
  1797.  
  1798.     def tell(self):
  1799.         """Return the position."""
  1800.         return self._pos
  1801.  
  1802.     def seek(self, offset, whence=0):
  1803.         """Change position."""
  1804.         if whence == 1:
  1805.             self._file.seek(self._pos)
  1806.         self._file.seek(offset, whence)
  1807.         self._pos = self._file.tell()
  1808.  
  1809.     def close(self):
  1810.         """Close the file."""
  1811.         del self._file
  1812.  
  1813.     def _read(self, size, read_method):
  1814.         """Read size bytes using read_method."""
  1815.         if size is None:
  1816.             size = -1
  1817.         self._file.seek(self._pos)
  1818.         result = read_method(size)
  1819.         self._pos = self._file.tell()
  1820.         return result
  1821.  
  1822.  
  1823. class _PartialFile(_ProxyFile):
  1824.     """A read-only wrapper of part of a file."""
  1825.  
  1826.     def __init__(self, f, start=None, stop=None):
  1827.         """Initialize a _PartialFile."""
  1828.         _ProxyFile.__init__(self, f, start)
  1829.         self._start = start
  1830.         self._stop = stop
  1831.  
  1832.     def tell(self):
  1833.         """Return the position with respect to start."""
  1834.         return _ProxyFile.tell(self) - self._start
  1835.  
  1836.     def seek(self, offset, whence=0):
  1837.         """Change position, possibly with respect to start or stop."""
  1838.         if whence == 0:
  1839.             self._pos = self._start
  1840.             whence = 1
  1841.         elif whence == 2:
  1842.             self._pos = self._stop
  1843.             whence = 1
  1844.         _ProxyFile.seek(self, offset, whence)
  1845.  
  1846.     def _read(self, size, read_method):
  1847.         """Read size bytes using read_method, honoring start and stop."""
  1848.         remaining = self._stop - self._pos
  1849.         if remaining <= 0:
  1850.             return ''
  1851.         if size is None or size < 0 or size > remaining:
  1852.             size = remaining
  1853.         return _ProxyFile._read(self, size, read_method)
  1854.  
  1855.  
  1856. def _lock_file(f, dotlock=True):
  1857.     """Lock file f using lockf and dot locking."""
  1858.     dotlock_done = False
  1859.     try:
  1860.         if fcntl:
  1861.             try:
  1862.                 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
  1863.             except IOError, e:
  1864.                 if e.errno in (errno.EAGAIN, errno.EACCES):
  1865.                     raise ExternalClashError('lockf: lock unavailable: %s' %
  1866.                                              f.name)
  1867.                 else:
  1868.                     raise
  1869.         if dotlock:
  1870.             try:
  1871.                 pre_lock = _create_temporary(f.name + '.lock')
  1872.                 pre_lock.close()
  1873.             except IOError, e:
  1874.                 if e.errno == errno.EACCES:
  1875.                     return  # Without write access, just skip dotlocking.
  1876.                 else:
  1877.                     raise
  1878.             try:
  1879.                 if hasattr(os, 'link'):
  1880.                     os.link(pre_lock.name, f.name + '.lock')
  1881.                     dotlock_done = True
  1882.                     os.unlink(pre_lock.name)
  1883.                 else:
  1884.                     os.rename(pre_lock.name, f.name + '.lock')
  1885.                     dotlock_done = True
  1886.             except OSError, e:
  1887.                 if e.errno == errno.EEXIST or \
  1888.                   (os.name == 'os2' and e.errno == errno.EACCES):
  1889.                     os.remove(pre_lock.name)
  1890.                     raise ExternalClashError('dot lock unavailable: %s' %
  1891.                                              f.name)
  1892.                 else:
  1893.                     raise
  1894.     except:
  1895.         if fcntl:
  1896.             fcntl.lockf(f, fcntl.LOCK_UN)
  1897.         if dotlock_done:
  1898.             os.remove(f.name + '.lock')
  1899.         raise
  1900.  
  1901. def _unlock_file(f):
  1902.     """Unlock file f using lockf and dot locking."""
  1903.     if fcntl:
  1904.         fcntl.lockf(f, fcntl.LOCK_UN)
  1905.     if os.path.exists(f.name + '.lock'):
  1906.         os.remove(f.name + '.lock')
  1907.  
  1908. def _create_carefully(path):
  1909.     """Create a file if it doesn't exist and open for reading and writing."""
  1910.     fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0666)
  1911.     try:
  1912.         return open(path, 'rb+')
  1913.     finally:
  1914.         os.close(fd)
  1915.  
  1916. def _create_temporary(path):
  1917.     """Create a temp file based on path and open for reading and writing."""
  1918.     return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
  1919.                                               socket.gethostname(),
  1920.                                               os.getpid()))
  1921.  
  1922. def _sync_flush(f):
  1923.     """Ensure changes to file f are physically on disk."""
  1924.     f.flush()
  1925.     if hasattr(os, 'fsync'):
  1926.         os.fsync(f.fileno())
  1927.  
  1928. def _sync_close(f):
  1929.     """Close file f, ensuring all changes are physically on disk."""
  1930.     _sync_flush(f)
  1931.     f.close()
  1932.  
  1933. ## Start: classes from the original module (for backward compatibility).
  1934.  
  1935. # Note that the Maildir class, whose name is unchanged, itself offers a next()
  1936. # method for backward compatibility.
  1937.  
  1938. class _Mailbox:
  1939.  
  1940.     def __init__(self, fp, factory=rfc822.Message):
  1941.         self.fp = fp
  1942.         self.seekp = 0
  1943.         self.factory = factory
  1944.  
  1945.     def __iter__(self):
  1946.         return iter(self.next, None)
  1947.  
  1948.     def next(self):
  1949.         while 1:
  1950.             self.fp.seek(self.seekp)
  1951.             try:
  1952.                 self._search_start()
  1953.             except EOFError:
  1954.                 self.seekp = self.fp.tell()
  1955.                 return None
  1956.             start = self.fp.tell()
  1957.             self._search_end()
  1958.             self.seekp = stop = self.fp.tell()
  1959.             if start != stop:
  1960.                 break
  1961.         return self.factory(_PartialFile(self.fp, start, stop))
  1962.  
  1963. # Recommended to use PortableUnixMailbox instead!
  1964. class UnixMailbox(_Mailbox):
  1965.  
  1966.     def _search_start(self):
  1967.         while 1:
  1968.             pos = self.fp.tell()
  1969.             line = self.fp.readline()
  1970.             if not line:
  1971.                 raise EOFError
  1972.             if line[:5] == 'From ' and self._isrealfromline(line):
  1973.                 self.fp.seek(pos)
  1974.                 return
  1975.  
  1976.     def _search_end(self):
  1977.         self.fp.readline()      # Throw away header line
  1978.         while 1:
  1979.             pos = self.fp.tell()
  1980.             line = self.fp.readline()
  1981.             if not line:
  1982.                 return
  1983.             if line[:5] == 'From ' and self._isrealfromline(line):
  1984.                 self.fp.seek(pos)
  1985.                 return
  1986.  
  1987.     # An overridable mechanism to test for From-line-ness.  You can either
  1988.     # specify a different regular expression or define a whole new
  1989.     # _isrealfromline() method.  Note that this only gets called for lines
  1990.     # starting with the 5 characters "From ".
  1991.     #
  1992.     # BAW: According to
  1993.     #http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html
  1994.     # the only portable, reliable way to find message delimiters in a BSD (i.e
  1995.     # Unix mailbox) style folder is to search for "\n\nFrom .*\n", or at the
  1996.     # beginning of the file, "^From .*\n".  While _fromlinepattern below seems
  1997.     # like a good idea, in practice, there are too many variations for more
  1998.     # strict parsing of the line to be completely accurate.
  1999.     #
  2000.     # _strict_isrealfromline() is the old version which tries to do stricter
  2001.     # parsing of the From_ line.  _portable_isrealfromline() simply returns
  2002.     # true, since it's never called if the line doesn't already start with
  2003.     # "From ".
  2004.     #
  2005.     # This algorithm, and the way it interacts with _search_start() and
  2006.     # _search_end() may not be completely correct, because it doesn't check
  2007.     # that the two characters preceding "From " are \n\n or the beginning of
  2008.     # the file.  Fixing this would require a more extensive rewrite than is
  2009.     # necessary.  For convenience, we've added a PortableUnixMailbox class
  2010.     # which does no checking of the format of the 'From' line.
  2011.  
  2012.     _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+"
  2013.                         r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*"
  2014.                         r"[^\s]*\s*"
  2015.                         "$")
  2016.     _regexp = None
  2017.  
  2018.     def _strict_isrealfromline(self, line):
  2019.         if not self._regexp:
  2020.             import re
  2021.             self._regexp = re.compile(self._fromlinepattern)
  2022.         return self._regexp.match(line)
  2023.  
  2024.     def _portable_isrealfromline(self, line):
  2025.         return True
  2026.  
  2027.     _isrealfromline = _strict_isrealfromline
  2028.  
  2029.  
  2030. class PortableUnixMailbox(UnixMailbox):
  2031.     _isrealfromline = UnixMailbox._portable_isrealfromline
  2032.  
  2033.  
  2034. class MmdfMailbox(_Mailbox):
  2035.  
  2036.     def _search_start(self):
  2037.         while 1:
  2038.             line = self.fp.readline()
  2039.             if not line:
  2040.                 raise EOFError
  2041.             if line[:5] == '\001\001\001\001\n':
  2042.                 return
  2043.  
  2044.     def _search_end(self):
  2045.         while 1:
  2046.             pos = self.fp.tell()
  2047.             line = self.fp.readline()
  2048.             if not line:
  2049.                 return
  2050.             if line == '\001\001\001\001\n':
  2051.                 self.fp.seek(pos)
  2052.                 return
  2053.  
  2054.  
  2055. class MHMailbox:
  2056.  
  2057.     def __init__(self, dirname, factory=rfc822.Message):
  2058.         import re
  2059.         pat = re.compile('^[1-9][0-9]*$')
  2060.         self.dirname = dirname
  2061.         # the three following lines could be combined into:
  2062.         # list = map(long, filter(pat.match, os.listdir(self.dirname)))
  2063.         list = os.listdir(self.dirname)
  2064.         list = filter(pat.match, list)
  2065.         list = map(long, list)
  2066.         list.sort()
  2067.         # This only works in Python 1.6 or later;
  2068.         # before that str() added 'L':
  2069.         self.boxes = map(str, list)
  2070.         self.boxes.reverse()
  2071.         self.factory = factory
  2072.  
  2073.     def __iter__(self):
  2074.         return iter(self.next, None)
  2075.  
  2076.     def next(self):
  2077.         if not self.boxes:
  2078.             return None
  2079.         fn = self.boxes.pop()
  2080.         fp = open(os.path.join(self.dirname, fn))
  2081.         msg = self.factory(fp)
  2082.         try:
  2083.             msg._mh_msgno = fn
  2084.         except (AttributeError, TypeError):
  2085.             pass
  2086.         return msg
  2087.  
  2088.  
  2089. class BabylMailbox(_Mailbox):
  2090.  
  2091.     def _search_start(self):
  2092.         while 1:
  2093.             line = self.fp.readline()
  2094.             if not line:
  2095.                 raise EOFError
  2096.             if line == '*** EOOH ***\n':
  2097.                 return
  2098.  
  2099.     def _search_end(self):
  2100.         while 1:
  2101.             pos = self.fp.tell()
  2102.             line = self.fp.readline()
  2103.             if not line:
  2104.                 return
  2105.             if line == '\037\014\n' or line == '\037':
  2106.                 self.fp.seek(pos)
  2107.                 return
  2108.  
  2109. ## End: classes from the original module (for backward compatibility).
  2110.  
  2111.  
  2112. class Error(Exception):
  2113.     """Raised for module-specific errors."""
  2114.  
  2115. class NoSuchMailboxError(Error):
  2116.     """The specified mailbox does not exist and won't be created."""
  2117.  
  2118. class NotEmptyError(Error):
  2119.     """The specified mailbox is not empty and deletion was requested."""
  2120.  
  2121. class ExternalClashError(Error):
  2122.     """Another process caused an action to fail."""
  2123.  
  2124. class FormatError(Error):
  2125.     """A file appears to have an invalid format."""
  2126.